const CO_CONFIRM_COLOR = '#f44336';
const CO_CANCEL_COLOR = '#aaa';
const CO_LOADING_CONTROLLER = {
    versions: new Map(),
    keyId: 1
};
export class DialogService {
    showLoading() {
        const id = ++CO_LOADING_CONTROLLER.keyId;
        if (CO_LOADING_CONTROLLER.versions.size == 0) {
            wx.showLoading({
                mask: true,
                title: '请求中...'
            });
        }
        CO_LOADING_CONTROLLER.versions.set(id, true);
        return {
            hide: function() {
                CO_LOADING_CONTROLLER.versions.delete(id);
                if (CO_LOADING_CONTROLLER.versions.size == 0) {
                    wx.hideLoading();
                }
            }
        }
    }

    alert(msg: string, onConfirm?: () => void) {
        wx.showModal({
            content: msg,
            showCancel: false,
            confirmText: '确定',
            confirmColor: CO_CONFIRM_COLOR,
            success: onConfirm
        });
    }

    confirm(msg: string, onConfirm?: () => void, onCancel?: () => void) {
        wx.showModal({
            content: msg,
            showCancel: true,
            confirmText: '确定',
            cancelText: '取消',
            confirmColor: CO_CONFIRM_COLOR,
            cancelColor: CO_CANCEL_COLOR,
            success: res => {
                if (res.confirm) {
                    onConfirm && onConfirm();
                } else if (res.cancel) {
                    onCancel && onCancel();
                }
            }
        });
    }

    public toast(message: string, duration = 2000) {
        return wx.showToast({
            title: message,
            icon: 'none',
            mask: false,
            duration
        })
    }
    /**
     * 返回需要的数据
     * @param task 异步任务
     * @param looadingMessage 执行任务的等待消息
     */
    async doAsync<T>(task: Promise<T>, successMessage: string = ''): Promise<T> {
        let loading = this.showLoading();
        let data: T;
        try {
            data = await task;
            if (successMessage) {
                this.alert(successMessage);
            }
            return data;
        } finally {
            try {
                loading.hide();
            } catch(e) {
                console.log('可能多次关闭loading无效');
            }
        }
    }
}